(function($){
    var client = new com.im.common.ajax();
    var loading = false;
    var param = {"pageInfo":{"pageNumber":1,"pageSize":10}};
    var planTypes;
    var columns=[[
        {field:'impleProjId',title:'',width:40,fitColumns:true,
            formatter: function(value,row,index){
                return  '<input type="radio" name="comp_item_chose_r" class="minimal" value='+index+'></input>';
            }},
        {field:'impleProjName',title:"实施项目名称",width:100,fitColumns:true},
        {field:'planProjName',title:"工程名称",width:100,fitColumns:true},
        {field:'developOrgName',title:"建设单位",width:100,fitColumns:true},
        {field:'startDt',title:"开工年",width:100,fitColumns:true},
        {field:'endDt',title:"完工年",width:100,fitColumns:true},
        {field:'leadingPersonName',title:"负责人",width:100,fitColumns:true},
        {field:'linkmanName',title:"联系人",width:100,fitColumns:true},
        {field:'linkmanTel',title:"联系电话",width:100,fitColumns:true,hidden:true},
        {field:'contentScale',title:"内容",width:100,fitColumns:true,formatter: function(value,row,index){
                if(value.length > 10){
                    return '<label title="'+value+'">'+value.substr(0,10)+'...</label>';
                }else{
                    return '<label title="'+value+'">'+value+'</label>';
                }
            }},
        {field:'statusName',title:"状态",width:100,fitColumns:true},
        {field:'description',title:"描述",width:100,fitColumns:true}
    ]];

    var methods = {
        init: function(options) {
            var o = $.extend({
                elmIdModal : "itemSearchModal",//需要展示的位置
                elmIdOrgModal : "unitSearchModal",//需要展示的位置
                elmIdOut : "itemOut",//单击时回填的文本框
                callbackFunc: function(projectId,projectName) {
                }
            }, options || {});

            var self = this;

            onInit(o);

            return this;
        },
        treeOnClickInner : function(self,opt){
            //加载数据
            return o.treeOnClick('1','test');
        }

    };

    function onInit(opt) {
        //渲染查询界面
        _render(opt);


    };



    function _render(opt){
        //获取模态框
        var modal = $("#"+opt.elmIdModal);
        //清空
        modal.empty();
        var pDiv = $($.parseHTML('  <div class="modal-dialog modal-lg myModal_lg" role="document">' +
            '    <div class="modal-content">' +
            '      <div class="modal-header">' +
            '        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>' +
            '        <h4 class="modal-title">项目搜索</h4>' +
            '      </div>' +
            '      <div class="modal-body modalGrayBg">' +
            '        <!--内容开始-->' +
            '        <div class="box box-default">' +
            '          <div class="box-header with-border">' +
            '            <div class="row">' +
            '              <div class="col-md-12">' +
            '' +
            '                <div class="form-inline">' +
            '                  <div class="form-group">' +
            '                    <label>所属规划：</label>' +
            '                      <select id="comp_item_plan_type_sel" class="form-control select2">' +
            '                      </select>' +
            '                  </div>' +
            '                  <div class="form-group">' +
            '                    <label>工程名称：</label>' +
            '                    <input id="comp_item_project_name_input" type="text" class="form-control" placeholder="请输入工程名称"/>' +
            '                  </div>' +
            '                  <div class="form-group">' +
            '                    <label>实施项目名称：</label>' +
            '                    <input id="comp_item_item_name_input" type="text" class="form-control" placeholder="请输入项目名称"/>' +
            '                  </div>' +
            '                    <div class="form-group">' +
            '                      <label>建设单位：</label>' +
            '                      <div class="input-group">' +
            '                        <input id="comp_item_org_name_input" type="text" class="form-control" disabled="disabled"/>' +
            '                        <span class="input-group-btn">' +
            '                          <button id="comp_item_org_search_btn" class="btn btn-default" type="button">' +
            '                            <i class="fa fa-search"></i>' +
            '                          </button>' +
            '                        </span>' +
            '                      </div>' +
            '                    </div>' +
            '                  <button id="comp_item_search_btn" type="submit" class="btn btn-info"><i class="fa fa-search"></i> 查询</button>' +
            '                </div>' +
            '' +
            '              </div>' +
            '            </div>' +
            '          </div>' +
            '              <div class="box-body">' +
            '                <div class="myTable">' +
            '                  <table id="comp_item_list_tab" class="table table-bordered table-striped">' +
            '                  </table>' +
            '                  <div class="myPage">' +
            '                    <div id="comp_item_page_div"></div>' +
            '                  </div>' +
            '                </div>' +
            '              </div>' +
            '        </div>' +
            '      <!--内容结束-->' +
            '      </div>' +
            '' +
            '      <div class="modal-footer">' +
            '        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>' +
            '        <button id="comp_item_ensure_btn" type="button" class="btn btn-primary">确定</button>' +
            '      </div>' +
            '    </div>' +
            '  </div>'));
        modal.append(pDiv);
        $("#"+opt.elmIdModal).modal("show");

        //事件渲染
        //计划类型
        _renderPlanTypeList();
        //单位选择
        $("#comp_item_org_search_btn").click(function () {
            $("#comp_item_org_name_input").unitSearchCommpent({
                elmIdOut : "comp_item_org_name_input",//组织树单击之后回填的文本框（input）
                elmIdModal : opt.elmIdOrgModal,
                hasOrgType: true,//组织树是否先展示组织类型
                callbackFunc: function (orgId, orgName) {//组织树单击之后回调函数
                    //_callBackOrg(orgId, orgName);
                    param.developOrg = orgId;
                    _doSearchPage(1,param);
                }
            });
        });
        //查询
        $("#comp_item_search_btn").click(function () {
            _doSearchPage(1,param);
        });
        //确认
        $("#comp_item_ensure_btn").click(function(){
            _returnFunc(opt);
        });

    };
    function _doSearchPage(index,param){
        param.planProjName = $("#comp_item_project_name_input").val();
        param.planProjClass = $("#comp_item_plan_type_sel").val();
        param.impleProjName = $("#comp_item_item_name_input").val();
        param.pageInfo.pageNumber = index;
        param.pageInfo.pageSize = 10;
        param.sort = "start_dt";
        param.order = "desc";
        var result = client.callAsJson("projectInfoService/queryImpleProjList", param);
        if (result.success) {
            _showListUi(result.result);
        } else {
            toastr.error(result.resultMsg);
            return;
        }
    }

    /**
     * 规划类型
     * @private
     */
    function _renderPlanTypeList() {
        if(planTypes == undefined){
            var result = client.callAsJson("projectInfoService/queryPlanProjClassConstList", {});
            if (!result.success) {
                toastr.error('服务器忙，规划工程类型查询失败！'+result.resultMsg);
                return;
            }
            planTypes = result.result;
        }

        //规划类型列表添加元素
        $("#comp_item_plan_type_sel").append('<option value="">全部</option>');
        $.each(planTypes, function (i, item) {
            $("#comp_item_plan_type_sel").append('<option value="'+item.paramValValue+'">'+item.paramValName+'</option>');
        });
        $('.select2').select2();
    };

    function _showListUi(result){

        $("#comp_item_list_tab").datagrid({
            view : detailview,
    	    nowrap:false,
    	    fitColumns:true,
            columns : columns,
            data : result.rows,
            detailFormatter: function(value, rows){
                return  '<div style="padding:0px"><table class="ddv"></table></div>';
            },
            onExpandRow: function(index,row){
                var ddv = $(this).datagrid('getRowDetail',index).find('table.ddv');
                ddv.datagrid({
                    columns : columns,
                    data : row.subList
                });
            }
        });

        //页码
        $("#comp_item_page_div").pagination({
            total : result.total,
            pageSize : result.pageSize,
            pageNumber : result.pageNumber,
            pageList : [10 , 20],
            beforePageText:  '第' ,
            afterPageText: '页 共'+result.totalPages+'页',
            displayMsg: '共 '+result.total+'条记录',
            onSelectPage: function (pageNumber, pageSize) {
                param.pageInfo.pageNumber = pageNumber;
                param.pageInfo.pageSize = pageSize;
                _doSearchPage(pageNumber,param);
            }
        });
    };
    function _returnFunc(opt){
        var idx = $("input[name='comp_item_chose_r']:checked").val();
        if(idx != undefined){
            var project = $('#comp_item_list_tab').datagrid('getData').rows[idx];
            if(opt.elmIdOut != null && opt.elmIdOut != undefined){
                $("#"+opt.elmIdOut).val(project.impleProjName);
                $("#"+opt.elmIdOut).attr("projectId",project.impleProjId);
            }
            $("#"+opt.elmIdModal).modal("hide");
            return opt.callbackFunc(project.impleProjId,project.impleProjName);
        }else{
            toastr.warning("您未选择任何项目!!");
        }
    };
    
    $.fn.itemSearchCommpent = function(method) {

        if (methods[method] && method.charAt(0) != '_') {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' +  method + ' does not exist on jQuery.pagination');
        }
    };

})(jQuery);